#!/usr/bin/env python3
# coding:utf-8
import cv2 as cv


class TimeCounter(object):
    """
    用来测量算法消耗时间的工具，简单包装了一下cv.getTickCount()和cv.getTickFrequency()函数,
    测时代码本身耗时也需要消耗一点时间. 在实验过程中发现测时函数消耗的时间大约是所测量图像函数
    时间的百分之一.

    在OpenCV 3.4.0, python2.7下测试, 硬件i5 8250U, 通过设置性能模式改变CPU运行频率, 用任务
    管理器查看CPU频率, 省电模式下, CPU保持默频1.6Ghz, 高性能模式下, CPU频率3.3Ghz-3.8Ghz,
    测试两种性能模式下运行相同代码所用时间的变化. 实验发现, 两种情况下
    cv.getTickFrequency()返回值不变, cv.getTickCount()返回值减半, 显然Frequency不是CPU, 猜
    测OpenCV内部有一个时钟(文档中的TickMeter), 上述两个函数记录的是这个时钟的周期计数和频率.
    """
    def __init__(self):
        self._last_count = 0

    def start(self):
        self._last_count = cv.getTickCount()

    def get_delta_count(self):
        """
        获取距离上一次运行本函数或self.start() 所消耗的周期数, 时间等参数.
        example:
            c = TimeCounter()
            c.get_delta_count()  # or c.start(), start to count
            do_something()
            print(c.get_delta_count())

        :return: (delta_count, frequency(Mhz), delta_t(s))
        """
        curr_count = cv.getTickCount()  # current count
        freq = cv.getTickFrequency()
        delta_count = curr_count - self._last_count
        self._last_count = curr_count

        delta_t = delta_count/freq

        return delta_count, freq/1024/1024, delta_t


if __name__ == '__main__':
    counter = TimeCounter()
    for i in range(10):
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print(counter.get_delta_count())
        print("loop %i" % i)
